<template>
  <div class="config-email">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>邮箱配置</h3>
        </div>
      </template>

      <el-form :model="configForm" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="SMTP地址"
              prop="smtp"
              :rules="[{ required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }]"
            >
              <el-input
                v-model="configForm.smtp"
                placeholder="请输入SMTP服务器地址"
                style="width: 240px; display: inline-block"
              />
              <span style="color: #999; font-size: 12px; margin-left: 5px">
                如：QQ邮箱的SMTP服务器地址是smtp.qq.com，163邮箱的SMTP服务器地址是smtp.163.com
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="协议端口号"
              prop="smtp_port"
              :rules="[{ required: true, message: '请输入端口', trigger: 'blur' }]"
            >
              <el-input
                v-model="configForm.smtp_port"
                placeholder="请输入端口"
                style="width: 240px; display: inline-block"
              />
              <span style="color: #999; font-size: 12px; margin-left: 5px">
                如：QQ邮箱的ssl协议方式端口号是465/587，163邮箱的ssl协议方式端口号是465/994
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="邮箱账户"
              prop="smtp_user"
              :rules="[{ required: true, message: '请输入邮箱用户名', trigger: 'blur' }]"
            >
              <el-input
                v-model="configForm.smtp_user"
                placeholder="请输入邮箱用户名"
                style="width: 240px; display: inline-block"
              />
              <span style="color: #999; font-size: 12px; margin-left: 5px">
                如：gougucms@qq.com
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="邮箱密码"
              prop="smtp_pwd"
              :rules="[{ required: true, message: '请输入邮箱密码', trigger: 'blur' }]"
            >
              <el-input
                v-model="configForm.smtp_pwd"
                type="password"
                placeholder="请输入邮箱密码"
                style="width: 240px; display: inline-block"
                show-password
              />
              <span style="color: #999; font-size: 12px; margin-left: 5px">
                不一定是登录密码，如QQ邮箱的是第三方授权登录码，要自己去开启，在邮箱的设置->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="发送人"
              prop="from"
              :rules="[{ required: true, message: '请输入要显示的发送者', trigger: 'blur' }]"
            >
              <el-input
                v-model="configForm.from"
                placeholder="请输入要显示的发送者"
                style="width: 240px; display: inline-block"
              />
              <span style="color: #999; font-size: 12px; margin-left: 5px">
                用于展示给发送方，如：勾股CMS系统管理员
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="显示的邮箱"
              prop="email"
              :rules="[{ required: true, message: '请输入要显示的发送者邮箱', trigger: 'blur' }]"
            >
              <el-input
                v-model="configForm.email"
                placeholder="请输入要显示的发送者邮箱"
                style="width: 240px; display: inline-block"
              />
              <span style="color: #999; font-size: 12px; margin-left: 5px">
                可以不同于上面的账户，用于展示给发送方的邮箱，如：admin@gougucms.com
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="邮件模板">
          <el-input
            v-model="configForm.template"
            type="textarea"
            :rows="6"
            placeholder="请输入邮件模板内容"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">立即提交</el-button>
          <el-button @click="sendTestEmail">发送测试</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 测试邮件接收邮箱对话框 -->
    <el-dialog v-model="testDialogVisible" title="输入接收测试邮件的邮箱" width="400px">
      <el-form :model="testForm" :rules="testRules" ref="testFormRef">
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="testForm.email" placeholder="请输入接收测试邮件的邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="testDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSendTest">发送</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from '@/utils/request'

  // 表单数据
  const configForm = reactive({
    id: 0,
    smtp: '',
    smtp_port: '',
    smtp_user: '',
    smtp_pwd: '',
    from: '',
    email: '',
    template: '',
  })

  // 测试邮件相关
  const testDialogVisible = ref(false)
  const testForm = reactive({
    email: '',
  })

  const testRules = {
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    ],
  }

  const testFormRef = ref()

  // 获取邮件配置
  const getEmailConfig = async () => {
    try {
      const response = await axios.get('/home/conf/email')

      if (response.data?.code === 0) {
        Object.assign(configForm, response.data.data)
      } else {
        ElMessage.error(response.data?.msg || '获取邮箱配置失败')
      }
    } catch (error) {
      ElMessage.error('获取邮箱配置失败')
    }
  }

  // 提交表单
  const submitForm = async () => {
    try {
      const response = await axios.post('/home/conf/edit', configForm)

      if (response.data?.code === 0) {
        ElMessage.success('保存成功')
      } else {
        ElMessage.error(response.data?.msg || '保存失败')
      }
    } catch (error) {
      ElMessage.error('保存失败')
    }
  }

  // 发送测试邮件
  const sendTestEmail = () => {
    testForm.email = ''
    testDialogVisible.value = true
  }

  // 处理发送测试邮件
  const handleSendTest = () => {
    testFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const response = await axios.post('/index/email_test', { email: testForm.email })

          if (response.data?.code === 0) {
            ElMessage.success('测试邮件发送成功')
            testDialogVisible.value = false
          } else {
            ElMessage.error(response.data?.msg || '测试邮件发送失败')
          }
        } catch (error) {
          ElMessage.error('测试邮件发送失败')
        }
      }
    })
  }

  // 重置表单
  const resetForm = () => {
    getEmailConfig()
  }

  // 初始化
  onMounted(() => {
    getEmailConfig()
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
</style>
